"""
数据库连接管理
"""
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.exc import SQLAlchemyError
from backend.app.utils.config import settings
from backend.app.utils.logger import logger

try:
    # 创建数据库引擎
    engine = create_engine(
        settings.DATABASE_URI,
        pool_pre_ping=True,  # 自动检测断开的连接
        pool_recycle=3600,   # 一小时后回收连接
        echo=True,          # 打印SQL语句，方便调试
        connect_args={
            "charset": "utf8mb4"
        }
    )
    
    # 创建会话工厂
    SessionLocal = sessionmaker(
        autocommit=False,
        autoflush=False,
        bind=engine
    )
    
    logger.info("数据库连接成功")
except SQLAlchemyError as e:
    logger.error(f"数据库连接失败: {str(e)}")
    raise

# 声明基础模型
Base = declarative_base()

def get_db() -> Session:
    """
    获取数据库会话
    
    Yields:
        Session: 数据库会话
    """
    db = SessionLocal()
    try:
        yield db
    except SQLAlchemyError as e:
        logger.error(f"数据库操作失败: {str(e)}")
        db.rollback()
        raise
    finally:
        db.close() 